package com.example.system01.controller;

import com.example.system01.entity.Suppliers;
import com.example.system01.service.SuppliersService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/suppliers")
public class SuppliersController {
    @Autowired
    SuppliersService suppliersService;
    @Autowired
    HttpServletRequest request;
    @RequestMapping("/suppliersList")
    public String suppliersList(Model model){
        Object username = request.getSession().getAttribute("username");
        if(username==null){
            return "redirect:/";
        }else {
            model.addAttribute("username",username);
            List<Suppliers> suppliersList = suppliersService.findAll();
            //        System.out.println(suppliersList);
            model.addAttribute("data", suppliersList);
            return "suppliers/suppliersList";
        }
    }
    @RequestMapping("/suppliersAddProcess")
    public String suppliersAddProcess(@RequestParam String suppliersname, @RequestParam String addr
            , @RequestParam String phone){
        //        组装一个goods实例
        Suppliers suppliers = new Suppliers();
        suppliers.setSuppliersname(suppliersname);
        suppliers.setAddr(addr);
        suppliers.setPhone(phone);
        System.out.println(suppliers);
//        调用service的add方法给数据库
        if(suppliersService.add(suppliers)==1){
            //        如果返回ok，那么就进入商品管理首页
            return "redirect:/suppliers/suppliersList";
        }
        else{
            return "suppliers/suppliersList";
        }
    }
    @RequestMapping("/suppliersUpdate")
    public String update(Model model,@RequestParam String id){
        Object username = request.getSession().getAttribute("username");
        if(username==null){
            return "redirect:/";
        }else{
            Suppliers suppliers=new Suppliers();
            suppliers.setId(Integer.valueOf(id));
//        调用service方法查询出来该记录的数据信息
            Suppliers suppliersDB = suppliersService.findOne(suppliers);
//        2.将这些数据信息返回给视图
            model.addAttribute("username",username);
            model.addAttribute("data",suppliersDB);
//        3.返回视图文件
            return "suppliers/suppliersUpdate";
        }
//        首先基于id查询出来该id记录里的所有数据信息

    }
}
